package com.caseeye.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.caseeye.command.LoginInfo;
import com.caseeye.service.LoginService;

import com.caseeye.exception.LoginException;

@Component
@RequestMapping
public class LoginController {

	private LoginService loginService;

	@Required
	@Resource
	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	@RequestMapping(value = "/alogin", method = RequestMethod.POST)
	public String login(LoginInfo loginInfo, Model model, HttpSession session) {
		try {
			loginService.login(loginInfo.getLoginId(), loginInfo.getPassword());

			session.setAttribute("loginInfo", loginInfo);

			model.addAttribute("message", "login successful");

		} catch (Exception le) {
			if (le instanceof LoginException) {
				return "login";
			} else {
				throw new RuntimeException(le);
			}
		}
		return "redirect:index";
	}

	@RequestMapping(value = "/alogin", method = RequestMethod.GET)
	public String login() {
		return "login";
	}
}
